/*
 * @Descripttion: 
 * @Author: 人生只如初见
 * @Date: 2021-09-27 14:02:31
 * @LastEditors: 人生只如初见
 * @LastEditTime: 2021-09-27 16:55:12
 */
import * as THREE from "three";
import { screenToWebgl } from '../../utils'
import { selectRoadMaterial, roadMaterial } from '../../material'
export  class Select{
  constructor(editor){
    this.editor = editor
    this.type = 'selected'
    this.selected = null
    this.raycaster = new THREE.Raycaster();
  }
   /**
   * @function: 监听事件
   */
  listen() {
    this.editor.container.addEventListener('click', this.handleClick)
    this.editor.container.addEventListener('pointermove', this.handleMouseMove)
  }
  /**
   * @function: 销毁事件
   */
  dispose() {
    this.editor.container.removeEventListener('click', this.handleClick)
    this.editor.container.removeEventListener('pointermove', this.handleMouseMove)
    // this.editor.setState('none')
  }
  handleMouseMove = (event)=>{
     let mesh = this.select(event)
      if(mesh.length){
        let plane = mesh.find(mesh => mesh.isMesh)
        plane.material = selectRoadMaterial
        this.selected = plane
      }else{
        this.selected && (this.selected.material = roadMaterial)
        this.selected = null
      }
      this.editor.update()
  }
  handleClick=()=>{
    if(this.selected){
      this.editor.currentSelect = this.selected
      let points = this.selected.userData.points
      this.ponitMesh = this.editor.services.road.drawPoint(points)
      this.editor.addMesh(this.ponitMesh)
      // this.selected = null
    }else{
      this.editor.currentSelect.material = roadMaterial
      this.editor.currentSelect = null
      this.editor.removeMesh(this.ponitMesh)
    }
    this.editor.update()
  }
  select(event){
    let [x, y] = screenToWebgl(event)
    //通过鼠标单击位置标准设备坐标和相机参数计算射线投射器`Raycaster`的射线属性.ray
    this.raycaster.setFromCamera(new THREE.Vector2(x, y), this.editor.camera);
    // 未选中对象返回空数组[],选中一个数组1个元素，选中两个数组两个元素
    let intersects = this.raycaster.intersectObjects(this.editor.roadGroup.children, true);
    // intersects.length大于0说明，说明选中了模型
    let mesh = [];
    intersects = intersects.filter(v => v.object.name !== 'Land')
    console.log("射线器返回的对象", intersects);
    if (intersects.length > 0) {
      mesh = intersects.map(v => v.object)
    }
    return mesh
  }
}